package com.ydd.interceptor;

import com.ydd.constant.JwtClaimsConstant;
import com.ydd.context.BaseContext;
import com.ydd.properties.JwtProperties;
import com.ydd.utils.JwtUtil;
import com.ydd.vo.TokenVo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.prefs.Preferences;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
		//获取登录数据员工id
        //Long employeeId = (Long) request.getSession().getAttribute("employee");

        try {

            System.out.println("开始进行拦截");
            //获取请求头的令牌数据
            Object token = request.getHeader(jwtProperties.getAdminTokenName());
            System.out.println(token.toString());
            //解析令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token.toString());
            System.out.println(claims);
            //Long empId = (Long)claims.get(JwtClaimsConstant.EMP_ID) 注意：这是错误的，Long类型不可以这样转换，会发生报错
            String empId = claims.get("userId").toString() ;  //这是正确的
            BaseContext.setCurrentId(empId);
            //int转Long引用数据类型

            log.info("登录的员工id：{}",empId);
            //如果有登录数据，代表一登录，放行
            System.out.println("通过");
            return true;
        } catch (Exception e) {
            //否则，发送未认证错误信息
            //throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            //否则，发送未认证错误信息
            response.setStatus(401);
            return false;
        }

 }
}
